from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from router.router import register_routers
from fastapi_radar import Radar
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from core.base.api_mode import ApiResponse
from core.middleware.user_context_middleware import UserContextMiddleware

app = FastAPI(
    title="Case App",
    description="Case Management Application API",
    version="0.1.0",
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制为特定域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 用户上下文中间件：在请求范围内提供当前用户信息
app.add_middleware(UserContextMiddleware)

# 注册所有路由
register_routers(app)

radar = Radar(app)
radar.create_tables()


# 统一异常处理，包装为 ApiResponse
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content=ApiResponse(code=exc.status_code, msg=str(exc.detail), data=None).model_dump(),
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc: RequestValidationError):
    return JSONResponse(
        status_code=422,
        content=ApiResponse(code=422, msg="参数校验错误", data=exc.errors()).model_dump(),
    )


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000)
